package com.ki.erp.filter;

import com.ki.erp.constant.RedisConstant;
import com.ki.erp.operator.JwtOperator;
import com.ki.erp.operator.RedisOperator;
import com.ki.erp.vo.LoginUserVo;
import io.jsonwebtoken.ExpiredJwtException;
import jakarta.annotation.Resource;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    private @Resource JwtOperator jwtOperator;
    private @Resource RedisOperator redisOperator;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String token = request.getHeader("token");
        if (token == null) {
            filterChain.doFilter(request, response);
            return;
        }
        String userId;
        try {
            userId = jwtOperator.validateToken(token);
        } catch (ExpiredJwtException e) {
            throw new RuntimeException("登录已过期");
        }
        LoginUserVo loginUserVo = redisOperator.get(RedisConstant.TOKEN_PREFIX + userId);
        if (loginUserVo == null) {
            throw new RuntimeException("登录已过期");
        }
        SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(loginUserVo, null, null));
        filterChain.doFilter(request, response);
    }
}
